import { useMemberStore } from "@/stores"
import { promises } from "dns"

const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

// 添加拦截器
const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        // 1.非http开头需拼接地址
        if (!options.url.includes('http')) {
            options.url = baseUrl + options.url
        }
        // 2.请求默认时间
        options.timeout = 10000
        // 3.请求小程序请求头标识
        options.header = {
            ...options.header,
            'source-client': 'miniapp',
        }
        // 4.添加请求头
        const memberStore = useMemberStore()
        const token = memberStore.profile?.token
        if (token) {
            options.header.Authorization = token
        }
    },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFie', httpInterceptor)

interface Data<T> {
    code: string
    msg: string
    result: T
}

// 请求函数
// 添加类型，支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {
    // 返回promise对象
    return new Promise<Data<T>>((resolve, reject) => {
        uni.request({
            ...options,
            // 响应成功
            success: (res) => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data as Data<T>)
                } else if (res.statusCode === 401) {
                    // 清理用户信息，跳转重新登录
                    const memberStore = useMemberStore()
                    memberStore.clearProfile()
                    uni.navigateTo({ url: 'pages/login/login' })
                    reject(res)
                } else {
                    // 其他错误
                    uni.showToast({
                        icon: 'none',
                        title: (res.data as Data<T>).msg || '请求错误'
                    })
                    reject(res)

                }
            },
            //响应失败
            fail: (err) => {
                uni.showToast({
                    icon: 'none',
                    title: '网络错误'
                })
                reject(err)
            }
        })
    })
}